package top.jandmla.excel.util.excelReadImpl;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import top.jandmla.excel.bean.Test;
import top.jandmla.excel.util.ExcelRead;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Excel07Read implements ExcelRead {

    /**
     * 根据文本的第一个工作列表，读取数据
     *
     * @param file   文件类
     * @param nameid 文件ID
     * @param minId  最小数据ID
     * @return ExcelFile中的信息
     */
    @Override
    public List<Test> getTestFromSheet(File file, String nameid, String minId) {
        List<Test> list;
        //获取流
        FileInputStream fis = null;
        Workbook workbook;

        try {
            fis = new FileInputStream(file);
            workbook = new XSSFWorkbook(fis);
            Sheet sheet = workbook.getSheetAt(0);
            int rowCount = sheet.getPhysicalNumberOfRows();
            list = new ArrayList<>(rowCount);
            for (int i = 1; i < rowCount; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {
                    Test test = new Test();

                    Cell cell = row.getCell(0);
                    if (cell != null) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        test.setName(cell.getStringCellValue());
                    }

                    cell = row.getCell(1);
                    if (cell != null) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        test.setAge(Integer.valueOf(cell.getStringCellValue()));
                    }

                    cell = row.getCell(2);
                    if (cell != null) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        test.setPhone(cell.getStringCellValue());
                    }

                    cell = row.getCell(3);
                    if (cell != null) {
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        test.setEmail(cell.getStringCellValue());
                    }

                    test.setNameid(nameid);
                    list.add(test);
                }
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (file.exists())
                FileUtils.deleteQuietly(file);
        }
        return null;
    }
}
